<template>
  <MyModal ref="myModal" title="添加任务" :top="35">
    <template #content>
      <a-alert
        description="提醒：自动擦亮功能是基于对商品的秒级上下架操作实现，当前仅支持通过票达人发布的商品，您在闲鱼app发布的商品或通过其他工具发布的商品可能会操作失败"
        type="info"
        banner
        style="margin-bottom: 10px; padding: 10px"
      />

      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content1" v-if="current == 0">
        <div class="content-box">
          <div style="display: flex; width: 100%; align-items: center">
            <div>选择微信账号/选择闲鱼账号:</div>
            <a-select
              v-model:value="okRobat"
              @change="selectIndustry"
              placeholder="选择店铺"
              style="width: 255px; margin-left: 10px"
            >
              <a-select-option v-for="(item, index) in robatList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </div>
        </div>
        <div class="content-data">
          <div class="left">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <div>搜索宝贝标题:</div>
              <a-input
                v-model:value="searchValue"
                style="flex: 1; margin-left: 10px"
                placeholder="输入宝贝名称"
              >
                <template #prefix>
                  <SearchOutlined style="color: #858a99" />
                </template>
              </a-input>
            </div>
            <div class="checkbox-all">
              <a-checkbox v-model:checked="allCheck" @change="handelAllChecked">全选</a-checkbox>
            </div>
            <div class="left-box" ref="scrollBox" @scroll="handleScroll">
              <div
                class="left-item"
                v-for="(item, index) in goodsList"
                :key="item.id"
                v-if="goodsList.length > 0"
              >
                <a-checkbox v-model:checked="item.state" @change="selectedGoodsItem(item, index)">
                  <div
                    style="margin-left: 20px; display: flex; align-items: center"
                    :title="item.title"
                    class="item-text"
                  >
                    <img
                      :src="item.image"
                      v-if="item.image"
                      style="width: 30px; height: 30px"
                      alt=""
                    />
                    <div class="good-title">{{ item.title }}</div>
                  </div>
                </a-checkbox>
              </div>

              <a-empty v-else></a-empty>
            </div>
            <div class="pageBox">{{ TemporaryList.length }}/{{ goodsList.length }}</div>
          </div>
          <div class="center" @click="handleClickTemporary">
            <ArrowRightOutlined style="font-size: 18px; color: #1890ff" />
          </div>
          <div class="right">
            <div class="right-box">
              <div
                class="right-item"
                v-for="(item, index) in selectedGoodsList"
                :key="item.id"
                :title="item.title"
                v-if="selectedGoodsList.length > 0"
              >
                <img :src="item.image" v-if="item.image" style="width: 30px; height: 30px" alt="" />
                <div class="good-title">{{ item.title }}</div>
                <div @click="deleteGoodsItem(index, item)">
                  <DeleteOutlined
                    style="font-size: 16px; color: #858a99; cursor: pointer"
                    class="delete-icon"
                  />
                </div>
              </div>
              <a-empty v-else></a-empty>
            </div>
            <div class="pageBox">{{ TemporaryList.length }}/{{ selectedGoodsList.length }}</div>
          </div>
        </div>
      </div>
      <div class="steps-content" v-if="current == 1">
        <a-form
          ref="formRef2"
          :rules="rules2"
          :model="formState"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          style="width: 100%"
        >
          <a-form-item label="任务日期" style="margin-left: 180px" name="TaskTime">
            <a-date-picker
              v-model:value="formState.TaskTime"
              @change="changeTime"
              placeholder="选择日期"
            />
          </a-form-item>
          <a-form-item label="任务时间段" style="margin-left: 180px">
            <div style="position: relative; display: flex">
              <a-time-picker
                v-model:value="formState.taskBeginTime"
                valueFormat="HH:mm:ss"
                placeholder="开始时间"
              />
              <a-time-picker
                v-model:value="formState.taskEndTime"
                valueFormat="HH:mm:ss"
                placeholder="结束时间"
              />
            </div>
          </a-form-item>
          <a-form-item label="擦亮时间段" style="margin-left: 180px">
            <div style="position: relative; display: flex">
              <a-time-picker
                v-model:value="startValue"
                valueFormat="HH:mm:ss"
                placeholder="开始时间"
                :disabled="!formState.taskBeginTime && !formState.taskEndTime"
              />
              <a-time-picker
                v-model:value="endValue"
                valueFormat="HH:mm:ss"
                placeholder="结束时间"
                :disabled="!formState.taskBeginTime && !formState.taskEndTime"
              />
              <a-button
                type="primary"
                style="position: absolute; top: 0; right: -100px"
                @click="addTime1"
                ghost
              >
                添加
              </a-button>
            </div>
          </a-form-item>

          <div class="polishing" v-if="PolishingTimeIntervalArr.length > 0">
            <div
              v-for="(item, index) in PolishingTimeIntervalArr"
              class="polishing-item"
              :key="item"
            >
              <a-tag color="blue" @close="polishingLog(index)" closable>
                {{ item.polishBeginTime }} - {{ item.polishEndTime }}
              </a-tag>
            </div>
          </div>
        </a-form>
      </div>
      <div class="steps-content" v-if="current == 2">
        <a-form
          ref="formRef3"
          :rules="rules3"
          :model="formState"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          style="width: 100%"
          @finish="onFinish"
        >
          <a-form-item
            label="擦亮任务备注"
            style="margin-left: 180px"
            name="remark"
            :rules="[{ required: true, message: '请输入擦亮备注!' }]"
          >
            <a-input type="text" style="margin-left: 20px" v-model:value="formState.remark" />
          </a-form-item>

          <a-form-item
            label="擦亮间隔开始"
            style="margin-left: 180px"
            name="polishIntervalBeginTime"
            :rules="[{ required: true, message: '请输入擦亮开始时间!' }]"
          >
            <a-input
              suffix="分钟"
              type="number"
              style="margin-left: 20px"
              v-model:value="formState.polishIntervalBeginTime"
            />
          </a-form-item>

          <a-form-item
            label="擦亮间隔结束"
            style="margin-left: 180px"
            name="polishIntervalEndTime"
            :rules="[{ required: true, message: '请输入擦亮结束时间!' }]"
          >
            <a-input
              suffix="分钟"
              style="margin-left: 20px"
              type="number"
              v-model:value="formState.polishIntervalEndTime"
            />
          </a-form-item>

          <a-form-item
            label="循环方式"
            style="margin-left: 180px"
            name="LoopMode"
            :rules="[{ required: true, message: '请选择循环方式!' }]"
          >
            <a-radio-group
              v-model:value="formState.LoopMode"
              :disabled="true"
              :options="LoopModeList"
              @change="handleChangeRadio"
              class="selectShop"
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="steps-action">
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
        <a-button
          v-if="current == steps.length - 1"
          type="primary"
          html-type="submit"
          @click="onFinish"
        >
          完成
        </a-button>
        <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">上一步</a-button>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import * as accountApi from '@/api/account'
import * as xyApi from '@/api/xy'
import { message } from 'ant-design-vue'
import {
  timeStamp,
  areIntervalsNonOverlapping,
  parseTimeToMinutes,
  timeFormatYMD,
} from '@/hooks/util'
const labelCol = {
  style: { width: '100px', textAlign: 'center' },
}
const wrapperCol = { span: 10 }
const formRef2 = ref()
const formRef3 = ref()
const searchValue = ref('')
const searchTimer = ref(null)
//监听搜索框
watch(searchValue, newVal => {
  if (newVal) {
    goodsParams.value.title = newVal
    goodsParams.value.pageSize = 10
    if (searchTimer.value) {
      clearTimeout(searchTimer.value)
    }
    searchTimer.value = setTimeout(() => {
      getGoods(okRobat.value, 0)
    }, 200)
  }
})

let stamp = Date.now()
let today = timeFormatYMD(stamp)
// console.log('today=', today)

import dayjs, { Dayjs } from 'dayjs'
//总的表单数据
interface formState {
  TaskTime?: string | number
  PolishingTime?: [any, any]
  polishIntervalBeginTime?: number | string
  polishIntervalEndTime?: number | string
  LoopMode?: number | string
  taskBeginTime?: string
  taskEndTime?: string
  remark?: string
}
const formState = ref<formState>({
  taskBeginTime: '09:00:00',
  taskEndTime: '21:00:00',
  polishIntervalBeginTime: '3',
  polishIntervalEndTime: '3',
  LoopMode: '1',
  TaskTime: dayjs(today, 'YYYY-MM-DD'),
})
// 后缀为1 的是任务时间 2 擦亮时间段  3 擦亮时间间隔
//第一步的数据选择喝处理
const goodsList = ref([]) //左边的数据
const allCheck = ref(false) //总选中框
const selectedGoodsList = ref([]) //右边的数据
const TemporaryList = ref([]) //暂存的数据
const goodsParams = ref({ currentPage: 1, pageSize: 10 })

//初始化表当
const initForm = () => {
  // formState.value.polishIntervalBeginTime = ''
  current.value = 0
  // formState.value.polishIntervalEndTime = ''
  // formState.value.taskBeginTime = ''
  // formState.value.taskEndTime = ''
  // formState.value.LoopMode = ''
  // PolishingTimeIntervalArr.value = []
  selectedGoodsList.value = []
  // formState.value.TaskTime = ''
  allCheck.value = false
  selectedGoodsList.value = [] //右边的数据
  TemporaryList.value = []
  getGoods(okRobat.value, 0)
  formState.value.remark = ''
}

// 获取宝贝列表 0 筛选 1 分页
const getGoods = async (robotId: any, type: any) => {
  goodsParams.value.robotId = robotId
  try {
    let { state, data, message: msg } = await xyApi.getPolishGoods(goodsParams.value)
    if (state === 200) {
      data.forEach(item => {
        item.state = false
      })
      if (type) {
        goodsList.value = [...goodsList.value, ...data]
        allCheck.value = goodsList.value.every(item => item.state)
      } else {
        goodsList.value = data
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
//选择宝贝到右侧
const handleClickTemporary = () => {
  if (TemporaryList.value.length) {
    TemporaryList.value.forEach((item1: any) => {
      // selectedGoodsList.value.//右边数据
      const isInSelectedList = selectedGoodsList.value.some((item2: any) => item1.id === item2.id)
      if (!isInSelectedList) {
        selectedGoodsList.value.push(item1)
      }
    })
  }
}
//全选操作
const handelAllChecked = e => {
  if (e.target.checked) {
    goodsList.value.forEach(item => {
      item.state = true
      const isInSelectedList = TemporaryList.value.some(existingItem => existingItem.id === item.id)
      if (!isInSelectedList) {
        TemporaryList.value.push(item)
      }
    })
  } else {
    goodsList.value.forEach(item => {
      item.state = false
    })
    TemporaryList.value = []
  }
}
//全选判断
const isCheckedAll = () => {
  return goodsList.value.every(item => item.state)
}
//右侧选择项 处理
const selectedGoodsItem = async (item: any, index: any) => {
  if (item.state) {
    TemporaryList.value.push(item)
  } else {
    // 如果复选框被取消选中，从 TemporaryList 中移除 item
    const indexToRemove = TemporaryList.value.findIndex(listItem => listItem.id === item.id)
    if (indexToRemove !== -1) {
      TemporaryList.value.splice(indexToRemove, 1)
    }
  }
  allCheck.value = await isCheckedAll()
}
//删除宝贝项
const deleteGoodsItem = async (index: any, item: any) => {
  TemporaryList.value.splice(index, 1)
  selectedGoodsList.value.splice(index, 1)
  goodsList.value.forEach(row => {
    if (row.id === item.id) {
      row.state = false
    }
  })
  allCheck.value = await isCheckedAll()
}
//店铺列表
let okRobat = ref<string>()
import type { SelectProps } from 'ant-design-vue'

const robatList = ref<SelectProps['options']>([])
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list.map(item => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
      selectRobat(data.list[0].id)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: unknown) => {
  okRobat.value = selectValue as string
  getGoods(okRobat.value, 0)
}
//监听店铺选择
watch(okRobat, newVal => {
  goodsParams.value.currentPage = 1
  allCheck.value = false
  searchValue.value = ''
  goodsParams.value.pageSize = 10
  delete goodsParams.value.title
  getGoods(newVal, 0)
})
//滚动scroll
const scrollBox = ref()
const handleScroll = () => {
  if (scrollBox.value.scrollTop + scrollBox.value.clientHeight >= scrollBox.value.scrollHeight) {
    // 滚动到底部的逻辑
    goodsParams.value.currentPage++
    getGoods(okRobat.value, 1)
    // 例如，你可以在这里发起一个请求来加载更多数据
  }
}

//循环模式
const LoopModeList = ref([
  {
    label: '单次循环',
    value: '1',
  },
  {
    label: '每日循环',
    value: '2',
  },
])
//循环选择
const handleChangeRadio = (e: any) => {
  formState.value.LoopMode = e.target.value
}
let spBizType = ref<string>('')
import type { SelectProps } from 'ant-design-vue'
const selectIndustry = (selectValue: any) => {
  spBizType.value = selectValue as string
}
//时间
// 将选择范围控制在7天
//时间处理
import 'dayjs/locale/zh-cn'
import type { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined
const startValue = ref<string>()
const endValue = ref<string>()
//擦亮时间端
const PolishingTimeIntervalArr = ref<Array<any>>([
  {
    polishBeginTime: '09:00:00',
    polishEndTime: '10:00:00',
  },
  {
    polishBeginTime: '11:00:00',
    polishEndTime: '12:00:00',
  },
  {
    polishBeginTime: '14:00:00',
    polishEndTime: '15:00:00',
  },
  {
    polishBeginTime: '16:00:00',
    polishEndTime: '17:00:00',
  },
])
const polishingLog = (index: any) => {
  PolishingTimeIntervalArr.value.splice(index, 1)
  // console.log('PolishingTimeIntervalArr=', PolishingTimeIntervalArr.value)
}
//添加时间
const addTime1 = () => {
  // formRef2.value.resetFields()
  formState.value.PolishingTime = []
  if (!startValue.value || !endValue.value) {
    return
  }
  if (formState.value.taskBeginTime >= formState.value.taskEndTime) {
    message.error('没有在任务时间段内')
    formState.value.taskBeginTime = ''
    formState.value.taskEndTime = ''
    return
  }
  let isTimeRangeValid = true
  if (startValue.value && endValue.value) {
    // 转换为分钟
    const startTimeMinutes = parseTimeToMinutes(startValue.value)
    const endTimeMinutes = parseTimeToMinutes(endValue.value)

    // 验证开始时间和结束时间
    const startTimeValid = startTimeMinutes >= parseTimeToMinutes(formState.value.taskBeginTime)
    const endTimeValid = endTimeMinutes <= parseTimeToMinutes(formState.value.taskEndTime)

    // 验证开始时间早于或等于结束时间
    const orderValid = startTimeMinutes <= endTimeMinutes

    isTimeRangeValid = startTimeValid && endTimeValid && orderValid
  } else {
    isTimeRangeValid = false
  }
  if (!isTimeRangeValid) {
    message.error('没有在任务时间段内')
    startValue.value = ''
    endValue.value = ''

    return
  }
  if (endValue.value <= startValue.value) {
    message.error('结束时间不能小于开始时间')
    return
  }
  if (PolishingTimeIntervalArr.value.length > 9) {
    message.error('最多只能选择10个时间段')

    return
  }
  PolishingTimeIntervalArr.value.push({
    polishBeginTime: startValue.value,
    polishEndTime: endValue.value,
  })
  startValue.value = ''
  endValue.value = ''

  console.log('PolishingTimeIntervalArr=', PolishingTimeIntervalArr.value)
}

//步骤
const steps = [
  {
    title: '请选择要擦亮的宝贝',
    content: 'First-content',
  },
  {
    title: '设置任务开始日期及时间段',
    content: 'Second-content',
  },
  {
    title: '擦亮间隔与方式',
    content: 'Last-content',
  },
]
const current = ref<number>(0)
const next = () => {
  if (selectedGoodsList.value.length <= 0) {
    message.error('未选择宝贝啊~')

    return
  }
  current.value++
}
//监听当前的 步骤
watch(current, newVal => {
  if (newVal == 2) {
    if (!formState.value.TaskTime) {
      message.error('未选择任务日期~')
      current.value--
      return
    }
    if (PolishingTimeIntervalArr.value.length <= 0) {
      message.error('未选择时间段啊~')
      current.value--
      return
    }
    const nonOverlapping = areIntervalsNonOverlapping(PolishingTimeIntervalArr.value)
    // console.log(nonOverlapping) // 输出 true 或 false
    if (!nonOverlapping) {
      message.error('当前时间段不可有交叉~')
      current.value--
      return
    }
  }
})
//上一步
const prev = () => {
  current.value--
}

//模态框ref
const myModal = ref()

const showModal = () => {
  myModal.value?.showModal()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

//最后提交
const onFinish = async () => {
  if (!formState.value.polishIntervalBeginTime) {
    message.error('未填写擦亮开始时间~')
    return
  } else if (!formState.value.polishIntervalEndTime) {
    message.error('未填写擦亮结束时间~')
    return
  } else if (!formState.value.LoopMode) {
    message.error('未选择循环方式~')
    return
  }
  if (
    Number(formState.value.polishIntervalEndTime) < Number(formState.value.polishIntervalBeginTime)
  ) {
    message.error('擦亮结束时间需要大于擦亮开始时间~')
    return
  }
  if (!formState.value.remark) {
    message.error('请填写任务备注~')
    return
  }

  try {
    const productList = selectedGoodsList.value.map(item => {
      return {
        itemId: item.itemId,
        title: item.title,
        robotId: item.robotId,
      }
    })

    let data = {
      polishIntervalBeginTime: formState.value.polishIntervalBeginTime,
      polishIntervalEndTime: formState.value.polishIntervalEndTime,
      startState: 0,
      taskBeginTime: formState.value.taskBeginTime,
      taskEndTime: formState.value.taskEndTime,
      circulationType: formState.value.LoopMode,
      polishTimeList: PolishingTimeIntervalArr.value,
      polishProductList: productList,
      taskExecuteTime: timeStamp(formState.value.TaskTime),
      remark: formState.value.remark,
    }
    console.log(data, 'data')

    const { state, message: msg } = await xyApi.addPolishTask(data)
    if (state === 200) {
      message.success('新增成功')
      //将表单置为初始状态
      initForm()
      myModal.value?.cancelModal()
      emit('refresh')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
onMounted(() => {
  getRobatList()
})
</script>
<style lang="less">
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  padding: 80px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.steps-content1 {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  padding: 40px 40px 0 40px;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  .content-box {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    // justify-content: space-between;
  }
  .content-data {
    width: 100%;
    .pageBox {
      text-align: left;
      width: 100%;
      margin-top: 10px;
      margin-left: 10px;
      font-size: 12px;
      color: #1890ff;
    }

    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      display: flex;
      flex-direction: column;
      // align-items: center;
      position: relative;
      .checkbox-all {
        position: absolute;
        left: 12px;
        top: 50px;
        z-index: 999;
      }
      .left-box {
        margin-top: 50px;
        width: 350px;
        height: 320px;
        border: 2px solid #eee;
        border-radius: 5px;
        overflow-y: scroll;
        padding: 10px;
        .left-item {
          display: flex;
          align-items: center;
          .good-title {
            margin-left: 10px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
        .left-item:nth-child(n + 2) {
          margin-top: 4px;
        }
        .left-item:nth-child(2n) {
          background-color: rgba(160, 220, 255, 0.5);
          padding: 5px;
          border-radius: 2px;
        }
        .left-item:nth-child(2n-1) {
          background-color: #fff;
          padding: 5px;
          border-radius: 2px;
        }
      }
    }
    .right {
      .right-box {
        margin-top: 80px;
        width: 350px;
        height: 320px;
        border: 2px solid #eee;
        border-radius: 5px;
        overflow-y: scroll;
        padding: 10px;

        .right-item {
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .good-title {
            margin-left: 10px;
            display: -webkit-box;

            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
        .right-item:nth-child(n + 2) {
          margin-top: 4px;
        }
        .right-item:nth-child(2n) {
          background-color: rgba(160, 220, 255, 0.5);
          padding: 5px;
          border-radius: 2px;
        }
        .right-item:nth-child(2n-1) {
          background-color: #fff;
          padding: 5px;
          border-radius: 2px;
        }
      }
    }
    .center {
      cursor: pointer;
    }
  }
}

.steps-action {
  margin-top: 24px;
}

.ant-steps .ant-steps-horizontal .ant-steps-label-horizontal {
  height: 300px !important;
}

.steps-action {
  margin-top: 24px;
}
.ant-steps .ant-steps-horizontal .ant-steps-label-horizontal {
  height: 300px !important;
}

[data-theme='dark'] .steps-content {
  background-color: #2f2f2f;
  border: 1px dashed #404040;
}

.ant-step {
  /* height: 100px !important; */
  display: flex;
  align-items: center;
  justify-content: space-around;
  .item {
  }
}
.active {
  color: red;
}
.polishing {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  flex-wrap: wrap;
  padding-left: 120px;
  .polishing-item {
  }
  .polishing-item:nth-child(n + 5) {
    margin-top: 10px;
  }
}
.ant-transfer-list-header-selected {
  // display: none;
}
.ant-transfer-list-header-dropdown {
  display: none !important;
}
</style>
